#include <iostream>
#include <ctime>
#include <unistd.h>
#include "RingQueue.hpp"
#include "Task.hpp"

using namespace std;

#define PRONUM 3
#define COMNUM 5

struct threadData
{
    RingQueue<Task> *rq;        //此处是环形队列而不是线程号
    string name;
};

void *Producer(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    RingQueue<Task> *rq = td->rq;
    string name = td->name;
    int len = oper.size();      //用一个变量接受，在下面的循环中就不用频繁调用了
    while(true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        char op = oper[rand() % len];
        usleep(1000);
        Task t(data1, data2, op);
        rq->Push(t);
        cout << name << " produce a task: " << t.GetTask() << endl;
    }
    delete td;
    return nullptr;     //记得写返回值
}

void *Consumer(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    RingQueue<Task> *rq = td->rq;
    string name = td->name;
    while(true)
    {
        sleep(1);
        Task t;
        rq->Pop(&t);
        t();
        cout << name << " get a task, result: " << t.GetResult() << endl;
    }
    delete td;
    return nullptr;     //记得写返回值
}

int main()
{
    srand(time(nullptr));
    RingQueue<Task> *rq = new RingQueue<Task>(10);
    pthread_t pro[PRONUM], com[COMNUM];
    for(int i = 0; i < PRONUM; ++i)
    {
        threadData *td = new threadData();
        td->rq = rq;
        td->name = "Producer-" + to_string(i);
        pthread_create(pro + i, nullptr, Producer, td);
    }
    for(int i = 0; i < COMNUM; ++i)
    {
        threadData *td = new threadData();
        td->rq = rq;
        td->name = "Consumer-" + to_string(i);
        pthread_create(com + i, nullptr, Consumer, td);
    }

    for(int i = 0; i < PRONUM; ++i)
    {
        pthread_join(pro[i], nullptr);
    }
    for(int i = 0; i < COMNUM; ++i)
    {
        pthread_join(com[i], nullptr);
    }

    delete rq;


    return 0;
}